<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('新增信用评分')" />
    <th:block th:include="include :: select2-css" />
    <th:block th:include="include :: bootstrap-select-css" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInLeft ibox-content">
        <form class="form-horizontal m" id="form-grade-add">
            <div class="form-group">
                <label class="col-sm-2 control-label is-required">信用评分名称：</label>
                <div class="col-sm-8">
                    <input name="gradeName" class="form-control" type="text" required>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label is-required">地区：</label>
                <div class="col-sm-3">
                    <select id="city" name="city" class="form-control m-b" th:with="type=${@dict.getType('b_city')}" required>
                        <option>请选择</option>
                        <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                    </select>
                </div>

                <label class="col-sm-2 control-label is-required">周期类型：</label>
                <div class="col-sm-3">
                    <select id="periodType" name="periodType" class="form-control m-b" th:with="type=${@dict.getType('b_period_type')}" required>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label is-required">模板：</label>
                <div class="col-sm-3">
                    <select id="templateId" name="templateId" class="form-control m-b" required>
                    </select>
                </div>
                <label class="col-sm-2 control-label is-required">考核周期：</label>
                <div class="col-sm-3">
                    <input id="gradePeriod" name="gradePeriod" class="form-control" type="text" required>
                    <span class="help-block m-b-none" style="color:red"><i class="fa fa-info-circle"></i> 考核周期数据格式示例：年度：2021，半年：2021上半年，季度：2021三季度，月度：202110</span>
                </div>
            </div>
            <div class="col-sm-12 select-table table-bordered">
                <table id="bootstrap-table"></table>
            </div>
            <div style="text-align:right;">
                <a class="btn btn-primary btn-rounded btn-sm" style="margin-top:10px;" onclick="submitHandler()"> 添加 </a>
            </div>

        </form>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: select2-js" />
    <th:block th:include="include :: bootstrap-select-js" />
    <script th:inline="javascript">
        //年月极度月
		Date.prototype.Format = function (fmt) { //author: meizz
				var o = {
					"M+": this.getMonth() + 1, //月份
					"d+": this.getDate(), //日
					"h+": this.getHours(), //小时
					"m+": this.getMinutes(), //分
					"s+": this.getSeconds(), //秒
					"q+": Math.floor((this.getMonth() + 3) / 3)==1?'一':(Math.floor((this.getMonth() + 3) / 3)==2?'二':(Math.floor((this.getMonth() + 3) / 3)==3?'三':'四')), //季度
					"n+": this.getMonth()>6?'下':'上', //半年
					"S": this.getMilliseconds() //毫秒
				};
				if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
				for (var k in o)
				if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
				return fmt;
			}
        var prefix = ctx + "system/grade"
        $("#form-grade-add").validate({
            focusCleanup: true
        });

        function submitHandler() {
            if ($.validate.form()) {
                $.operate.save(prefix + "/add", $('#form-grade-add').serialize());
                
                //更新查询页面
                var target = $('.Grade_iframe[data-id="/system/grade"]',parent.document);
                var url = target.attr('src');
                console.log("url="+url);
                target.attr('src', url).ready();

                $.modal.closeTab();
            }
        }

        //四级联动 开始
        $("#city").change(function () {//选择城市，填充周期类型
			$.ajax({
				url: ctx + "system/template/getPeriodType",
				type: 'GET',
				data: {
					city: $("#city").select2('val'),
				},
				success:function (data) {
				    console.log(data);
					$("#periodType").empty();
					$("#periodType").append("<option value=''>请选类型</option>");
					for (var i = 0; i < data.data.length; i++){
						$("#periodType").append("<option value='" + data.data[i].dictValue + "'>" + data.data[i].dictLabel + "</option>");
					}
				}
			});
		});

		$("#periodType").change(function () {//选择城市 周期类型，填充模板
			$.ajax({
				url: ctx + "system/template/getTemplate",
				type: 'GET',
				data: {
					city: $("#city").select2('val'),
					periodType: $("#periodType").select2('val')
				},
				success:function (data) {
				    console.log(data);
					$("#templateId").empty();
					$("#templateId").append("<option value=''>请选模板</option>");
					for (var i = 0; i < data.data.length; i++){
						$("#templateId").append("<option value=" + data.data[i].id + ">" + data.data[i].templateName + "</option>");
					}
					//填充考核周期
					var selectedPeriodType = $("#periodType").select2('val');
					if(selectedPeriodType==1){
					    $("#gradePeriod").val(new Date().Format("yyyy"));
					}else if(selectedPeriodType==2){
					    $("#gradePeriod").val(new Date().Format("yyyyn半年"));
					}else if(selectedPeriodType==3){
					    $("#gradePeriod").val(new Date().Format("yyyyq季度"));
					}else{
					    $("#gradePeriod").val(new Date().Format("yyyyMM"));
					}
				}
			});
		});


        //四级联动 结束

        $("#templateId").on('select2:select', function (e) {
          console.log($("#city").select2('val'));
          ajaxTable($("#templateId").select2('val'));
        });

        // 动态获取列
        function ajaxTable(templateId) {
        	var url = ctx + "system/template/getTemplateById";

        	$('#bootstrap-table').bootstrapTable('destroy');
            $.modal.loading("正在查询中，请稍后...");
            $.post(url, {"id":templateId}, function(result) {
                if (result.code == web_status.SUCCESS) {
                	setColumns(result.data,templateId);
                } else if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.msg)
                } else {
                    $.modal.alertError(result.msg);
                }
                $.modal.closeLoading();
            });
        }
      	// 设置列
        function setColumns(list,templateId) {
        	var columns = [];
        	list.forEach(function(item) {
        	    if($.common.equals('weight',item.field)){
        	    	columns.push(
                    {
                        field: 'weight',
                        title: '权重(%)',
                        formatter: function (value, row, index) {
                            if(typeof value === 'undefined' || value === null || value === ""){
                                return ''
                            }else{
                                return value+'%';
                            }
                        }
                    });
        	    } else {
        	    	columns.push({
        	    		field : item.field,
    					title : item.title
        	    	})
        	    }
        	});

        	columns.push(
                {
		            field: 'score',
		            align: 'center',
		            title: '自评分',
                    width:70,
		            formatter: function(value, row, index) {
		            	var html = $.common.sprintf("<input class='form-control' type='text' name='scores[%s]' value='%s' "
		            	            +" onkeyup = \"this.value=this.value.replace(/[^\\d-.]/g,'')\" "
		            	            +"onBlur=\"if(this.value>%s||this.value<%s){alert('请输入%s到%s之间的数');this.style.borderColor='red'}else{this.style.borderColor='black'}\""
		            	            +">", index, 0,row.inputMax,row.inputMin,row.inputMin,row.inputMax);
		        		return html;
                    }
		        }
	        );
	        columns.push(
                {
		            field: 'remark',
		            align: 'center',
		            title: '备注',
                    width:300,
		            formatter: function(value, row, index) {
		            	var html = $.common.sprintf("<textarea maxlength='500' class='form-control' rows='3' name='remarks[%s]' value=''></textarea>", index, 0);
		        		return html;
                    }
		        }
	        );

        	initTable(columns,templateId);

        }
      	// 刷新表格
        function refreshTable(columns) {
        	var options = {
        		columns: columns
        	};
        	$("#" + table.options.id).bootstrapTable('refreshOptions',options);
        }
      	// 初始化表格
        function initTable(columns,templateId){
        	var options = {
        		url: ctx + "system/template/getItemsByTemplateId?templateId="+templateId,
            	showSearch: false,
            	showRefresh: false,
            	showToggle: false,
            	showColumns: false,
            	pagination:false,

            	columns: columns,
            	onLoadSuccess : function(data) {
                    var data = $('#bootstrap-table').bootstrapTable(
                            'getData', true);
                    //合并单元格
                    columns.forEach(function(item) {
                        if($.common.equals('firstColumn',item.field)){
                            mergeCells($('#bootstrap-table'), data, "firstColumn", ["firstColumn"]);
                        } else if($.common.equals('secondColumn',item.field)){
                            mergeCells($('#bootstrap-table'), data, "secondColumn", ["firstColumn","secondColumn"]);
                        }else if($.common.equals('threeColumn',item.field)){
                            mergeCells($('#bootstrap-table'), data, "threeColumn", ["firstColumn","secondColumn","threeColumn"]);
                        }else if($.common.equals('fourColumn',item.field)){
                            mergeCells($('#bootstrap-table'), data, "fourColumn", ["firstColumn","secondColumn","threeColumn","fourColumn"]);
                        }else if($.common.equals('fiveColumn',item.field)){
                            mergeCells($('#bootstrap-table'), data, "fiveColumn", ["firstColumn","secondColumn","threeColumn","fourColumn","fiveColumn"]);
                        }else if($.common.equals('sixColumn',item.field)){
                            mergeCells($('#bootstrap-table'), data, "sixColumn", ["firstColumn","secondColumn","threeColumn","fourColumn","fiveColumn","sixColumn"]);
                        }
                    });
                }
            };
            $.table.init(options);
        }



        /**
		 * 合并单元格
		 * @param data 原始数据(在服务端完成排序)
		 * @param fieldName 合并属性名称
		 * @param colspan 合并列
		 * @param target 目标表格对象
		 */
		function mergeCells(target, data, fieldName, beforFields) {
			//声明一个map计算相同属性值在data对象出现的次数和
			var sortMap = {};
			for (var i = 0; i < data.length; i++) {
                var key='';
				for(var j=0;j< beforFields.length;j++){
					var beforField = beforFields[j];
					key += data[i][beforField];
				}

                if (sortMap.hasOwnProperty(key)) {
                    sortMap[key] = sortMap[key] * 1 + 1;
                } else {
                    sortMap[key] = 1;
                }
			}
			for ( var prop in sortMap) {
				console.log(prop, sortMap[prop])
			}
			var index = 0;
			for ( var prop in sortMap) {
				var count = sortMap[prop] * 1;
				$(target).bootstrapTable('mergeCells', {
					index : index,
					field : fieldName,
					colspan : 1,
					rowspan : count
				});
				index += count;
			}
		}

    </script>
</body>
</html>